package com.autoagent.ai_live_master.scriptGeneration.controller;

import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.scriptGeneration.dto.LoginDTO;
import com.autoagent.ai_live_master.scriptGeneration.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "02-认证管理", description = "用户认证相关接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Operation(summary = "用户登录", description = "用户登录接口，返回JWT令牌")
    @PostMapping("/login")
    public ApiResponse<String> login(
            @Parameter(description = "登录信息", required = true) 
            @RequestBody LoginDTO loginDTO) {
        log.info("收到登录请求 - 用户名: {}", loginDTO.getUsername());
        try {
            log.info("开始认证用户 - 用户名: {}", loginDTO.getUsername());
            String jwt = authService.authenticate(loginDTO.getUsername(), loginDTO.getPassword());
            if (jwt == null) {
                log.warn("用户认证失败 - 用户名: {}", loginDTO.getUsername());
                return ApiResponse.error(401, "用户登陆失败");
            } else {
                log.info("用户认证成功 - 用户名: {}", loginDTO.getUsername());
                return ApiResponse.success(jwt);
            }
        } catch (Exception e) {
            log.error("登录失败 - 用户名: {}, 错误信息: {}", loginDTO.getUsername(), e.getMessage(), e);
            return ApiResponse.error(401, "登录失败: " + e.getMessage());
        }
    }
}